package utils

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type DownloadUtil struct {
	Url      string
	Filename string
}

/** Download2browser
* 下载到浏览器
 */
func (u *DownloadUtil) Download2browser(c *gin.Context) {
	response, err := http.Get(u.Url)
	log.Println("后台请求资源..")
	if err != nil || response.StatusCode != http.StatusOK {
		c.String(http.StatusServiceUnavailable, "资源暂时无法访问，稍后重试")
		c.Abort()
		log.Fatalln("后台下载失败")
	}

	reader := response.Body
	contentLength := response.ContentLength
	contentType := response.Header.Get("Content-Type")

	extraHeaders := map[string]string{
		"Content-Disposition": fmt.Sprintf("attachment; filename=\"%s\"", u.Filename),
	}

	c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)

}
